package com.example.smartcity_poverty.CustomControl

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.ContextCompat
import com.example.smartcity_poverty.R

/**
 *  ANDROID STUDIO -VERSION 4.0
 *  email: 2506789532@qq.com
 *  CodeAuthor： Ikun
 *
 *  explain: 自定义ExitText
 **/
class CustomEditText @JvmOverloads constructor(
    context: Context?, attrs: AttributeSet? = null
) : androidx.appcompat.widget.AppCompatEditText(context, attrs){

    // 获取删除图标
    val iconDelete = ContextCompat.getDrawable(context!!, R.drawable.ic_baseline_clear_24)

    override fun onTextChanged(
        text: CharSequence?,
        start: Int,
        lengthBefore: Int,
        lengthAfter: Int
    ) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter)
        toggleClear()
    }

    /**
     * 计算点击删除按钮范围
     */
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.let { e ->
            iconDelete?.let { i ->
                if (
                    e.action == MotionEvent.ACTION_UP && e.x > width - i.intrinsicWidth
                    && e.x < width
                    && e.y > height / 2 - i.intrinsicHeight / 2
                    && e.y < height / 2 + i.intrinsicHeight / 2
                ) {
                    // 但点击删除按钮时清除输入框内容
                    text?.clear()
                }
            }
        }
        performClick()
        return super.onTouchEvent(event)
    }

    /**
     * 监听数量状态
     */
    private fun toggleClear() {
        val icon = if (text?.isNotEmpty() == true) iconDelete else null
        // 设置图标
        setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, icon, null)
    }
}